import router from '@/router';
import { store } from '..';
import { useUtilsStoreWithOut } from './utils';

interface UserInfo {
  username: string;
  token?: string;
  permissions: string[];
}
export const useUserInfo = defineStore('user-info', {
  state: (): { remember: UserInfo; notRemember: UserInfo; currentUserRouters: any[] } => ({
    remember: {
      username: '',
      token: '',
      permissions: [''],
    },
    notRemember: {
      username: '',
      token: '',
      permissions: [''],
    },
    currentUserRouters: [],
  }),
  getters: {
    getToken(state) {
      return state.remember.token || state.notRemember.token;
    },
    getUserName(state) {
      return state.remember.username || state.notRemember.username;
    },
    getPermissions(state) {
      return state.remember.permissions || state.notRemember.permissions;
    },
  },
  actions: {
    setUserInfo(state: boolean, obj: { username: string; permissions: string[] }) {
      state
        ? this.$patch({
            remember: {
              username: obj.username,
              permissions: obj.permissions,
            },
          })
        : this.$patch({
            notRemember: {
              username: obj.username,
              permissions: obj.permissions,
            },
          });
    },
    setToken(token: string) {
      this.$patch({
        remember: {
          token,
        },
        notRemember: {
          token,
        },
      });
    },
    // 登出
    logOut() {
      const utils = useUtilsStoreWithOut();
      this.$patch({
        remember: {
          username: '',
          token: '',
          permissions: [''],
        },
        notRemember: {
          username: '',
          token: '',
          permissions: [''],
        },
      });
      router.replace('/login');
      utils.clearHistoryRouter();
      const timer = setTimeout(() => {
        location.reload();
        clearTimeout(timer);
      }, 50);
    },
    setCurrentUSerRouters(routers: any) {
      this.currentUserRouters = routers;
    },
  },
  persist: {
    enabled: true,
    strategies: [
      {
        storage: localStorage,
        paths: ['remember'],
      },
      {
        storage: sessionStorage,
        paths: ['notRemember'],
      },
    ],
  },
});

export function useUserInfoStoreWithOut() {
  return useUserInfo(store);
}
